package www.ld.com.controller;

import cn.hutool.core.bean.BeanUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import www.ld.com.core.group.InsertGroup;
import www.ld.com.core.group.UpdateGroup;
import www.ld.com.domain.R;
import www.ld.com.domain.user.pojo.UserPO;
import www.ld.com.domain.user.query.UserQuery;
import www.ld.com.domain.user.vo.InUserVO;
import www.ld.com.domain.user.vo.OutUserVO;
import www.ld.com.domain.user.vo.UserVO;
import www.ld.com.domain.vo.PageRestVO;
import www.ld.com.service.UserService;
import www.ld.com.utils.PageUtils;

@Api(tags = "用户模块")
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping
    @ApiOperation(value = "查询用户列表")
    @PreAuthorize("hasAuthority('sys:user:select')")
    public  R<PageRestVO<UserVO>>  pageList(UserQuery userQuery) {
        PageRestVO pageRestVO = PageUtils.copyPageVO(userService.pageUserByUserQuery(userQuery), UserVO.class);
        return R.ok(pageRestVO);
    }
    @GetMapping("/{id}")
    @ApiOperation(value = "获取用户详情")
    @PreAuthorize("hasAuthority('sys:user:select')")
    public R<OutUserVO> getUserById(@PathVariable(value="id" ,required = true) String id){
        return R.ok(  userService.getOutUserVOById(id) );
    }
    @ApiOperation(value = "新增用户")
    @PostMapping
    @PreAuthorize("hasAuthority('sys:user:create')")
    public R save(@RequestBody @Validated(value = {InsertGroup.class})  InUserVO inUserVO) {
        userService.saveUserPO(BeanUtil.toBean(inUserVO, UserPO.class),inUserVO.getPostIds(),inUserVO.getRolesIds());
        return R.ok();
    }
    @ApiOperation(value = "修改用户")
    @PutMapping
    @PreAuthorize("hasAuthority('sys:user:update')")
    public R update(@RequestBody @Validated(value = {UpdateGroup.class}) InUserVO inUserVO) {
        userService.updateUserPOById(BeanUtil.toBean(inUserVO, UserPO.class),inUserVO.getPostIds(),inUserVO.getRolesIds());
        return R.ok();
    }
    @ApiOperation(value = "删除用户")
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('sys:user:delete')")
    public R delete(@PathVariable(value = "id", required = true) String id) {
        userService.deleteUserById(id);
        return R.ok();
    }
}
